package com.pug.mail.service.impl;

import com.pug.mail.bo.EmailAttachmentBO;
import com.pug.mail.dto.MySendMailReqDTO;
import com.pug.mail.service.IMailService;
import com.pug.mail.utils.EmailSendUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author RenGaoshuai
 * @date 2023/6/29 10:39
 * @description
 */
@Service
@Slf4j
public class MailServiceImpl implements IMailService {

    @Override
    public boolean sendMail(MySendMailReqDTO reqDTO) {
        return EmailSendUtil.sendMail(reqDTO.getSubject(), reqDTO.getTo(), reqDTO.getTest());
    }

    @Override
    public boolean sendMailAttachment(MySendMailReqDTO reqDTO) {

        EmailAttachmentBO attachment = new EmailAttachmentBO();
        attachment.setAttachmentName("批量审核接口改造CR.xlsx");
        attachment.setAttachmentUrl(null);

        byte[] bytes = InputStream2ByteArray("D:\\文档\\2023-01-01：CR-xxx-xxx-任高帅-xxx.xlsx");
        attachment.setAttachmentData(bytes);

        return EmailSendUtil.sendMail(reqDTO.getSubject(), reqDTO.getTo(), reqDTO.getTest(), attachment);

    }


    private byte[] InputStream2ByteArray(String filePath) {
        try {
            InputStream in = new FileInputStream(filePath);
            byte[] data = toByteArray(in);
            in.close();

            return data;
        } catch (Exception e) {
            return null;
        }
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


}
